/**
 * ===========================================
 * Project: gamehistory-web
 * ===========================================
 * Package: com.cyou.gamehistory.front.web
 * 
 * Copyright (c) 2012, CYOU All Rights Reserved.
 * ===========================================
 */
package com.cyou.gamehistory.front.web;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cyou.annals.bean.News;
import com.cyou.annals.util.AnnalsClient;
import com.cyou.framework.exception.ExceptionUtility;
import com.cyou.framework.mapper.JsonMapper;
import com.cyou.framework.util.DateUtility;
import com.cyou.framework.util.StringUtility;
import com.cyou.gamehistory.entity.GameHistory;
import com.cyou.gamehistory.entity.UserInfo;
import com.cyou.gamehistory.entity.vo.Account;
import com.cyou.gamehistory.entity.vo.MemberInfo;
import com.cyou.gamehistory.service.GameHistoryService;
import com.cyou.gamehistory.service.UserInfoService;
import com.cyou.gamehistory.util.ApplicationConfig;
import com.cyou.gamehistory.util.ApplicationConstants;
import com.cyou.gamehistory.util.WebUtil;
import com.google.common.collect.Maps;

/**
 * <p>
 * SpaceController
 * </p>
 * 
 * @since 2012-12-7
 * @version
 * @author zhangxingkai
 */
@Controller
@RequestMapping(value = "/f/space")
public class SpaceController {
	private static final Logger logger = LoggerFactory
			.getLogger(SpaceController.class);

	@Autowired
	private GameHistoryService gameHistoryService;
	@Autowired
	private UserInfoService userInfoService;
	private final JsonMapper jsonMapper = JsonMapper.nonDefaultMapper();
	private static String requestUrl = ApplicationConfig.getValue("requestUrl");
	private static Map<Integer, Integer> gameYear = Maps.newLinkedHashMap();
	static {
		Integer year=DateUtility.now().getYear()+1900;
		for(int i=2001;i<=year;i++){
			gameYear.put(i, i);
		}
	}
	/**
	 * 查看我的编年史
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@RequestMapping(value = "")
	public String space(Model model, HttpSession session,HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		logger.info("进入spaceController...");

		// 校验是否登录
		// 未登录不可查看, 返回提示登录页面
		// 若已登录，查看是否已生成过编年史
		// 若没有生成，则跳转到 /f/gamehistory/edit
		// 如已生成，则查询我的编年史信息并显示
		Integer uid=WebUtil.returnUserId(request, response);
		UserInfo userinfo = userInfoService.getUserInfoByUserId(uid);
		if(userinfo==null){

			try{
				userinfo=new UserInfo();
				userinfo.setCreateTime(DateUtility.now());
				userinfo.setHonor("潜力级");
				logger.info("调用 getMemberInfo begin " );
				String jsonString=AnnalsClient.getMemberInfo(uid);
				logger.info("调用 getMemberInfo end jsonString=== "+ jsonString);
				MemberInfo memberinfo=jsonMapper.fromJson(jsonString, MemberInfo.class);
				Account account=memberinfo.getAccount();
				if(account!=null){
					logger.info("passport==="+ account.getAccId());
					userinfo.setNickname(account.getNickname());
					userinfo.setPassport(account.getAccId());
					userinfo.setSmallImage(WebUtil.staticGetHeadshot(account.getAccId()));
				}
				userinfo.setCostCount(0d);
				userinfo.setGameCount(0);
				userinfo.setGameBeginTime(0);
				userinfo.setGameLastestTime(2012);
				userinfo.setStoryCount(0);
				userinfo.setUpdateCount(0);
				userinfo.setUserId(uid);
				userInfoService.saveUserInfo(userinfo);
				
			}catch(Exception e){
				logger.error("保存新用户失败  ", e);
				throw ExceptionUtility.unchecked(e);
			}
			
		
		}
		
		//判断他的编年史tab页面是否打开
		UserInfo hisGameHistoryCloseFlag=(UserInfo) session.getAttribute("hisGameHistoryCloseFlag");
		if(hisGameHistoryCloseFlag!=null&&!hisGameHistoryCloseFlag.getUserId().equals(uid)){
			model.addAttribute("hisSpace", hisGameHistoryCloseFlag);
		}else{
			session.removeAttribute("hisGameHistoryCloseFlag");
		}
		
		//获取我的编年史页面十条数据
		List<GameHistory> gameHistoryList = gameHistoryService.getGameHistoryList(userinfo.getUserId());
		//获取所有数据
		List<GameHistory> gameAllHistoryList = gameHistoryService.getAllGameHistoryList(userinfo.getUserId());
		//将list转换成map，方便页面循环显示
		Map<String, List<GameHistory>> gameHistoryMap = gameHistoryService.getMapList(gameAllHistoryList);
		//获取用户前十条数据具有的年份
		List<String> historyYears = gameHistoryService.getHistoryYears(userinfo.getUserId());
		if (gameHistoryList != null && gameHistoryList.size() > 0&& historyYears != null) {
			Map<String, List<GameHistory>> map = gameHistoryService.getGameHistoryMap(gameHistoryList, historyYears);
			if (gameAllHistoryList.size() > 10) {
				model.addAttribute("isMore", "true");
			}
			if (gameAllHistoryList.size() < 16) {
				model.addAttribute("noNeedPage", "true");
			}
			if (gameAllHistoryList.size() <=75) {
				model.addAttribute("noPage", "true");
			}
			News news=gameHistoryService.getRandomNews();
			model.addAttribute("news", news);
			Integer userCount = userInfoService.userCount();
			Integer rank=userInfoService.calculateRank(userinfo.getUserId());
			model.addAttribute("rank", rank);
			String imagePath=ApplicationConfig.getValue("annalsImage.imagePath");
			model.addAttribute("imagePath", imagePath);
			model.addAttribute("userCount", userCount);
			model.addAttribute("historyMap", map);
			model.addAttribute("userinfo", userinfo);
			model.addAttribute("gameHistoryList", gameHistoryList);
			model.addAttribute("gameHistoryMap", gameHistoryMap);
		} else {
			logger.info("else space  ... url=="+requestUrl+"/f/gamehistory/edit");
			request.getRequestDispatcher("/f/gamehistory/edit").forward(request, response);
			return null;
		}
		logger.info(" 11 space url");
		return "/front/space";
	}

	/**
	 * 修改我的编年史
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@RequestMapping(value = "modify")
	public String modifyspace(Model model, HttpSession session,HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		logger.debug("进入spaceController...");

		UserInfo userinfo = userInfoService.getUserInfoByUserId(WebUtil.returnUserId(request, response));
		if (userinfo == null) {
			// 返回登录
			return "/front/login";
		}

		List<GameHistory> gameHistoryList = gameHistoryService.getAllGameHistoryListByOrderNum(userinfo.getUserId());
		if (gameHistoryList != null && gameHistoryList.size() > 0) {
			model.addAttribute("size", gameHistoryList.size() + 1);
			model.addAttribute("userinfo", userinfo);
			model.addAttribute("gameYear", gameYear);
			model.addAttribute("gameHistoryList", gameHistoryList);
		} else {
			request.getRequestDispatcher("/f/gamehistory/edit").forward(request, response);
			return null;
		}
		return "/front/edit";
	}

	/**
	 * 查看某人的编年史
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@RequestMapping(value = "{id}")
	public String othersSpace(@PathVariable("id") Integer id, Model model,HttpSession session,HttpServletRequest request,HttpServletResponse response,String refer) throws ServletException, IOException {
		refer=this.getRefer(refer);
		UserInfo sessionUser= userInfoService.getUserInfoByUserId(WebUtil.returnUserId(request, response));
		UserInfo userinfo=userInfoService.getUserInfoByUserId(id);
		if(userinfo==null){
			return "error/500";
		}
		if(sessionUser!=null){
			if(id.equals(sessionUser.getUserId())){
				return this.space(model, session,request,response);
			}
		}
		List<GameHistory> gameAllHistoryList = gameHistoryService.getAllGameHistoryList(id);
		Map<String, List<GameHistory>> gameHistoryMap = gameHistoryService.getMapList(gameAllHistoryList);
		List<GameHistory> gameHistoryList = gameHistoryService.getGameHistoryList(id);
		List<String> historyYears = gameHistoryService.getHistoryYears(id);
		if (gameHistoryList != null && gameHistoryList.size() > 0&& historyYears != null) {
			Map<String, List<GameHistory>> map = gameHistoryService.getGameHistoryMap(gameHistoryList, historyYears);
			if (gameAllHistoryList.size() > 10) {
				model.addAttribute("isMore", "true");
			}
			if (gameAllHistoryList.size() <16) {
				model.addAttribute("noNeedPage", "true");
			}
			if (gameAllHistoryList.size() <=75) {
				model.addAttribute("noPage", "true");
			}
			Integer userCount = userInfoService.userCount();
			Integer rank = userInfoService.calculateRank(userinfo.getUserId());
			model.addAttribute("userCount", userCount);
			model.addAttribute("rank", rank);
			model.addAttribute("refer",refer );
			model.addAttribute("historyMap", map);
			model.addAttribute("userinfo", userinfo);
			model.addAttribute("gameHistoryList", gameHistoryList);
			model.addAttribute("gameHistoryMap", gameHistoryMap);
		}else{
			
			model.addAttribute("noResult", "true");
			return "/front/hisspace";
		}
		session.setAttribute("hisGameHistoryCloseFlag", userinfo);
		return "/front/hisspace";
	}
	/**
	 * 关闭他的编年史
	 * @param refer
	 * @return
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@RequestMapping(value = "close")
	public String closeHisHistory(HttpServletRequest request,HttpServletResponse response,String refer,HttpSession session) throws ServletException, IOException{
		session.removeAttribute("hisGameHistoryCloseFlag");
		refer=this.getRefer(refer);
		if(StringUtility.isNotBlank(refer)&&"edit".equals(refer)){
			request.getRequestDispatcher("/f/gamehistory/edit").forward(request, response);
			return null;
		}
		
		if(StringUtility.isNotBlank(refer)){
			request.getRequestDispatcher("/f/"+refer).forward(request, response);
			return null;
		}else{
			request.getRequestDispatcher("/f/index").forward(request, response);
			return null;
		}
	}
	/**
	 * 关闭他的编年史
	 * @param refer
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value = "ajaxClose")
	public void ajaxClose(HttpSession session,HttpServletResponse response) throws IOException{
		session.removeAttribute("hisGameHistoryCloseFlag");
		response.getWriter().print("true");
	}
	/**
	 *查看更多
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "more")
	@ResponseBody
	public List<GameHistory> myMore(HttpSession session,HttpServletRequest request,HttpServletResponse response) {
		UserInfo userinfo = userInfoService.getUserInfoByUserId(WebUtil.returnUserId(request, response));
		if (userinfo == null) {
			// 返回登录
		}
		List<GameHistory> gameHistoryList = gameHistoryService.getAllGameHistoryList(userinfo.getUserId());
		return gameHistoryList;
	}
	/**
	 * 查看他人编年史更多
	 * @param id
	 * @param model
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "more/{id}")
	@ResponseBody
	public List<GameHistory> more(@PathVariable("id") Integer id, Model model,
			HttpSession session) {
		List<GameHistory> gameHistoryList = gameHistoryService.getAllGameHistoryList(id);
		return gameHistoryList;
	}
	/**
	 * 20s 获取一条随机新闻信息
	 */
	@RequestMapping(value = "news")
	@ResponseBody
	public News ajaxNews() {
		News news=gameHistoryService.getRandomNews();
		return news;
	}
	public String getRefer(String refer){
		if(StringUtility.isNotBlank(refer)){
			if(!refer.equals("index")&&!refer.equals("space")&&!refer.equals("feed")&&!refer.equals("edit")){
				return "index";
			}
		}
		return refer;
	}

}
